package com.zyyyys.shuaicodeplatform.langgraph4j.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zyyyys.shuaicodeplatform.langgraph4j.model.ImageResource;
import com.zyyyys.shuaicodeplatform.langgraph4j.model.enums.ImageCategoryEnum;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 插画图片收集工具（优化版：含重试机制 + 随机等待 + 连接失败后返回指定默认插画）
 */
@Slf4j
@Component
public class UndrawIllustrationTool {

    private static final String UNDRAW_API_URL = "https://undraw.co/_next/data/mMWmJSt23qpgo8cLTD_pB/search/%s.json?term=%s";

    private static final int MAX_RETRIES = 5;
    private static final long MIN_RETRY_WAIT_MS = 1000L;
    private static final long MAX_RETRY_WAIT_MS = 10000L;

    private static final Random RANDOM = new Random();

    /**
     * 搜索插画图片工具方法
     *
     * @param query 搜索关键词，如果为空则默认使用 "happy"
     * @return 插画资源列表，可能为空（网络请求失败或无结果时）
     */
    @Tool("搜索插画图片，用于网站美化和装饰")
    public List<ImageResource> searchIllustrations(@P("搜索关键词") String query) {
        List<ImageResource> imageList = new ArrayList<>();

        if (StrUtil.isBlank(query)) {
            query = "happy";
            log.info("查询关键词为空，使用默认关键词: {}", query);
        }

        String apiUrl = String.format(UNDRAW_API_URL, query, query);

        for (int attempt = 0; attempt < MAX_RETRIES; attempt++) {
            try (HttpResponse response = HttpRequest.get(apiUrl)
                    .timeout(20000)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                    .header("Accept-Language", "en-US,en;q=0.9")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .header("Cache-Control", "no-cache")
                    .header("Pragma", "no-cache")
                    .header("Sec-Fetch-Dest", "document")
                    .header("Sec-Fetch-Mode", "navigate")
                    .header("Sec-Fetch-Site", "none")
                    .header("Sec-Fetch-User", "?1")
                    .header("Upgrade-Insecure-Requests", "1")
                    .execute()) {

                if (!response.isOk()) {
                    log.warn("第 {} 次尝试：请求未成功，状态码: {}", attempt + 1, response.getStatus());
                    if (attempt < MAX_RETRIES - 1) {
                        long waitMs = getRandomWaitTime();
                        log.info(" 第 {} 次尝试失败，状态码非200，等待 {} ms 后重试", attempt + 1, waitMs);
                        TimeUnit.MILLISECONDS.sleep(waitMs);
                    }
                    continue;
                }

                String responseBody = response.body();
                log.debug("第 {} 次尝试：API响应状态码: {}, 响应内容长度: {}", attempt + 1, response.getStatus(), responseBody.length());

                JSONObject result = JSONUtil.parseObj(responseBody);
                JSONObject pageProps = result.getJSONObject("pageProps");
                if (pageProps == null) {
                    log.warn("第 {} 次尝试：未找到 pageProps 数据", attempt + 1);
                    return imageList;
                }

                JSONArray initialResults = pageProps.getJSONArray("initialResults");
                if (initialResults == null || initialResults.isEmpty()) {
                    log.warn("第 {} 次尝试：未找到插画搜索结果", attempt + 1);
                    return imageList;
                }

                int actualCount = Math.min(12, initialResults.size());
                for (int i = 0; i < actualCount; i++) {
                    JSONObject illustration = initialResults.getJSONObject(i);
                    String title = illustration.getStr("title", "插画");
                    String media = illustration.getStr("media", "");
                    if (StrUtil.isNotBlank(media)) {
                        imageList.add(ImageResource.builder()
                                .category(ImageCategoryEnum.ILLUSTRATION)
                                .description(title)
                                .url(media)
                                .build());
                    }
                }

                log.info(" 第 {} 次尝试成功，获取到 {} 张插画图片", attempt + 1, imageList.size());
                return imageList;

            } catch (Exception e) {
                if (e.getCause() instanceof SocketException) {
                    log.warn("第 {} 次尝试时连接被重置: {}", attempt + 1, e.getMessage());
                } else {
                    log.error("第 {} 次尝试搜索插画失败：{}", attempt + 1, e.getMessage(), e);
                }

                if (attempt < MAX_RETRIES - 1) {
                    long waitMs = getRandomWaitTime();
                    log.info(" 第 {} 次尝试失败，等待 {} ms 后进行下一次重试", attempt + 1, waitMs);
                    try {
                        TimeUnit.MILLISECONDS.sleep(waitMs);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        log.warn("线程被中断，停止重试");
                        return getDefaultIllustration(); // 中断时返回默认插画
                    }
                } else {
                    log.error(" 搜索插画失败，已重试 {} 次，所有尝试均失败，返回默认插画", MAX_RETRIES);
                    return getDefaultIllustration(); // 所有重试失败后返回默认插画
                }
            }
        }

        // 正常情况下不会走到这里，但为了安全仍返回默认插画
        return getDefaultIllustration();
    }

    /**
     * 获取随机等待时间 [1000ms ~ 10000ms]
     */
    private long getRandomWaitTime() {
        return MIN_RETRY_WAIT_MS + RANDOM.nextInt((int) (MAX_RETRY_WAIT_MS - MIN_RETRY_WAIT_MS));
    }

    /**
     * 返回一个默认插画（指定 URL：https://undraw.co/illustrations/happy_day.svg）
     */
    private List<ImageResource> getDefaultIllustration() {
        log.info("🔁 使用默认插画（兜底数据）：https://undraw.co/illustrations/happy_day.svg");
        return Arrays.asList(
                ImageResource.builder()
                        .category(ImageCategoryEnum.ILLUSTRATION)
                        .description("默认插画：Happy Day")
                        .url("https://undraw.co/illustrations/happy_day.svg") // 你指定的默认插画链接
                        .build()
        );
    }
}